const mongo = require('../db/db.js')
const formidable = require('formidable')
const time = require('../../util/time.js')
const getId = require('../../util/getId.js')
module.exports = {
    addType:function (req,res) {
        let form = new formidable.IncomingForm();
        form.parse(req,function (err,files,file) {
            let typename = files.name;
            getId.getId('typeId',function (id) {
                mongo.insert('type',{name:typename,time:time.time(),id:id,count:0},function () {
                    res.json({
                        status:200,
                        msg:'增加成功'
                    })
                })
            });


        })
    },
    findType:function (req,res) {
        mongo.find('type',{},{id:-1},function (result) {
            res.json({
                status:200,
                msg:result
            })
        })
    },
    editType:function (req,res) {
        let id =  parseInt(req.query.id);
        let name = req.query.name;
       mongo.update('type',{'id':id},{$set:{name:name,time:time.time()}},function () {
           res.json({
               status:200,
               msg:'更改成功'
           })
       })
    },
    deleteType:function (req,res) {
        let id =  parseInt(req.query.id);
        mongo.del('type',{"id":id},function () {
            res.json({
                status:200,
                msg:'删除成功'
            })
        })
    },
    deleteMany:function (req,res) {
        let ids = req.query.ids.split(',');
        var index = 0
        for(let i=0;i<ids.length;i++){
            let id = parseInt(ids[i])
            mongo.del('type',{"id":id},function () {
                index++;
                if(index==ids.length-1){
                    res.json({
                        status:200,
                        msg:'删除成功'
                    })
                }

            })
        }

    }
}
